package org.facyt.commons.view.form;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.facyt.commons.view.bean.AbstractBeanForm;

import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Form;

public class GenericForm<T extends AbstractBeanForm> extends Form {

	private static final long serialVersionUID = 1L;
	
	protected BeanItem<T> beanItem;
	protected List<String> orderedPropertiesIds;
	
	public GenericForm(T bean) {
		super();
		init(bean);
	}
	
	protected void init(T bean){
		inicializarLayout();
		inicializarDataSource(bean);
		inicializarFieldFactory();
		setWriteThrough(false);
	}
	
	protected void inicializarLayout(){
		getLayout().setMargin(true, true, true, true);
	}
	
	protected void inicializarDataSource(T bean){
		this.setItemDataSource(new BeanItem<T>(bean));
	}
	
	/**
	 * 
	 * @param propertyId
	 * @param fieldGenerator
	 */
	public void addFieldGenerator(Object propertyId, FieldGenerator fieldGenerator) {
		((GenericFieldFactory) getFormFieldFactory()).addFieldGenerator(propertyId, fieldGenerator);
	}
	
	/**
	 * Agrega los caption
	 * @param caption
	 */
	public void addFielCaption(Map<String, String> caption){
		((GenericFieldFactory) getFormFieldFactory()).setCaptionFields(caption);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void setItemDataSource(Item newDataSource, Collection<?> propertyIds) {
		beanItem = (BeanItem<T>) newDataSource;
		
		if (orderedPropertiesIds != null){
			super.setItemDataSource(newDataSource, getOrderedPropertiesIds());
		}else
			super.setItemDataSource(newDataSource, propertyIds);
	}

	protected void inicializarFieldFactory(){
		setFormFieldFactory(new GenericFieldFactory());
	}

	public List<String> getOrderedPropertiesIds() {
		return orderedPropertiesIds;
	}
	
	public void setOrderedPropertiesIds(List<String> orderedPropertiesIds) {
		this.orderedPropertiesIds = orderedPropertiesIds;
	}
	
	public void setRequieredField(Map<String, Boolean> requiredFields){
		((GenericFieldFactory) getFormFieldFactory()).setRequiredFields(requiredFields);
	}
	
	public void setReadOnlyField(Map<String, Boolean> readOnlyFields){
		((GenericFieldFactory) getFormFieldFactory()).setReadOnlyFields(readOnlyFields);
	}	
	
	public BeanItem<T> getBeanItem() {
		return beanItem;
	}
	
	
}
